package org.artifact.core.plugin.agent;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.io.File;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.util.Map;

/**
 * Manifest-Version: 1.0
 * Agent-Class: org.artifact.core.lang.JavaAgent
 * Can-Redefine-Classes: true
 * Can-Retransform-Classes: true
 */
public class JavaAgent {
    private static final Log log = LogFactory.get(JavaAgent.class);

    public static void agentmain(String args, Instrumentation inst) throws Exception {
        log.debug("JavaAgent Start");
        JSONObject json = JSONUtil.parseObj(args);


        File tempFile = FileUtil.touch("temp/agent.log");

        FileUtil.appendString(DateUtil.now() + System.getProperty("line.separator"), tempFile, CharsetUtil.CHARSET_UTF_8);

        for (Map.Entry<String, Object> entry : json.entrySet()) {
            Class clazz = ClassUtil.loadClass(entry.getKey());
            byte[] data = FileUtil.readBytes(entry.getValue().toString());
            ClassDefinition classDefinition = new ClassDefinition(clazz, data);
            inst.redefineClasses(classDefinition);
            log.debug(clazz.getName());
            FileUtil.appendString(clazz.getName() + System.getProperty("line.separator"), tempFile, CharsetUtil.CHARSET_UTF_8);
        }
        log.debug("JavaAgent end");
    }
}